'use strict';
const db = uniCloud.database();
const dataCollection = db.collection('user_data');

exports.main = async (event, context) => {
  const { action, id, content, openid } = event;
  try {
    switch (action) {
      case 'add':
        // 添加数据
        const addRes = await dataCollection.add({
          content,
          openid,
          createTime: Date.now()
        });
        return {
          code: 0,
          message: '添加成功',
          data: addRes
        };
        
      case 'get':
        // 获取用户数据
        const getRes = await dataCollection.where({ openid }).get();
        return {
          code: 0,
          message: '获取成功',
          data: getRes.data
        };
        
      case 'update':
        // 更新数据
        const updateRes = await dataCollection.doc(id).update({
          content,
          updateTime: Date.now()
        });
        return {
          code: 0,
          message: '更新成功',
          data: updateRes
        };
        
      case 'delete':
        // 删除数据
        const deleteRes = await dataCollection.doc(id).remove();
        return {
          code: 0,
          message: '删除成功',
          data: deleteRes
        };
        
      default:
        return {
          code: -1,
          message: '无效的操作'
        };
    }
  } catch (err) {
    console.error('操作失败:', err);
    return {
      code: -1,
      message: '操作失败',
      error: err
    };
  }
};